import request from '@/utils/request'
import React, { useCallback, useEffect, useState } from 'react';
import { DatePicker, Select, Form, ConfigProvider, Space } from 'antd';
import moment from 'moment';
import { Redirect } from 'react-router';
const { Option } = Select;
const { RangePicker } = DatePicker;
//联级下拉选择
export function withSelector(InnerComponent) {
    return function OuterComponent(props) {
        const [selectForm] = Form.useForm();
        //楼栋选择
        const [buildings, setBuildings] = useState([]);
        const getBuildings = useCallback(async () => {
            const { data } = await request.get('/building/getManageBuildings');
            setBuildings(data.data.buildings);
        }, []);
        //楼栋选择回调
        const [buildingId, setBuildingId] = useState('');
        const handleChangeBuildings = useCallback((_, { key }) => {
            selectForm.setFieldsValue({ floor: '请选择', room: '请选择', student: '请选择' });
            setBuildingId(key);
            getFloors(key);
            setRoomId('');
            setUserId('');
            setFloorId('');
        }, [])

        //楼层选择
        const [floors, setFloors] = useState([]);
        const getFloors = useCallback(async id => {
            const { data } = await request.get('/floor/getFloors', { params: { buildingId: id } });
            setFloors(data.data.floors);
        }, [buildingId]);
        //楼层选择回调
        const [floorId, setFloorId] = useState('');
        const handleChangeFloors = useCallback((_, { key }) => {
            selectForm.setFieldsValue({ room: '请选择', student: '请选择' });
            setFloorId(key);
            getRooms(key);
            setRoomId('');
            setUserId('');
        }, [])

        //房间选择
        const [rooms, setRooms] = useState([]);
        const getRooms = useCallback(async id => {
            const { data } = await request.get('/room/getRooms', { params: { floorId: id } });
            setRooms(data.data.rooms);
        }, []);
        //房间选择回调
        const [roomId, setRoomId] = useState('');
        const handleChangeRooms = useCallback((_, { key }) => {
            selectForm.setFieldsValue({ student: '请选择' });
            setRoomId(key);
            getStudent(key);
            setUserId('');
        }, [])

        //学生选择
        const [students, setStudents] = useState([]);
        const getStudent = useCallback(async id => {
            const { data } = await request.get('/user/getStudents', { params: { roomId: id } });
            setStudents(data.data.users);
        }, []);
        //选择学生回调
        const [userId, setUserId] = useState('');
        const handleChangeStudents = useCallback((_, { key }) => {
            setUserId(key);
        }, [])

        //日期选择
        const [date, setDate] = useState([]);
        const onChange = useCallback((dates, dateStrings) => {
            setDate(
                dateStrings.map(item => {
                    return new Date(item).getTime()
                })
            )
        })

        //下拉选择
        const style = { width: 250 }
        const Selects = useCallback((values) => {
            return (
                <div className="selects" style={{ width: '100%' }}>

                    <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                        <Form

                            form={selectForm}
                            colon={false}
                            layout="inline"
                            initialValues={{ building: '请选择', floor: '请选择', room: '请选择', student: '请选择' }}
                        >

                            <Form.Item
                                style={style}
                                name="building"
                                label="宿舍楼"
                            >
                                <Select
                                    onSelect={handleChangeBuildings}
                                >
                                    {

                                        buildings.map(item => {
                                            return (
                                                <Option key={item.id} value={item.name}>{item.name}</Option>
                                            )
                                        })
                                    }
                                </Select>
                            </Form.Item>
                            <Form.Item
                                style={style}
                                name="floor"
                                label="楼层"
                                hidden={values.selectNum == 1}
                            >
                                <Select
                                    onSelect={handleChangeFloors}
                                    disabled={buildingId ? false : true}
                                >
                                    {

                                        floors.map(item => {
                                            return (
                                                <Option key={item.id} value={item.layer}>{item.layer}</Option>
                                            )
                                        })
                                    }
                                </Select>
                            </Form.Item>
                            <Form.Item
                                style={style}
                                name="room"
                                label="房间"
                                hidden={values.selectNum == 1 || values.selectNum == 2}
                            >
                                <Select
                                    onSelect={handleChangeRooms}
                                    disabled={floorId ? false : true}
                                >
                                    {

                                        rooms.map(item => {
                                            return (
                                                <Option key={item.id} value={item.number}>{item.number}</Option>
                                            )
                                        })
                                    }
                                </Select>
                            </Form.Item>
                            <Form.Item
                                style={style}
                                name="student"
                                label="学生"
                                hidden={values.selectNum == 1 || values.selectNum == 2 || values.selectNum == 3}
                            >
                                <Select
                                    onSelect={handleChangeStudents}
                                    disabled={roomId ? false : true}
                                >
                                    {

                                        students.map(item => {
                                            return (
                                                <Option key={item.id} value={item.name}>{item.name}</Option>
                                            )
                                        })
                                    }
                                </Select>
                            </Form.Item>

                        </Form>
                        {
                            values.btn ? values.btn : ''
                        }
                    </div>
                    {
                        !values.date ? "" :
                            <div style={{ marginTop: 20 }}>
                                <RangePicker size='default'
                                    onChange={onChange}
                                    ranges={{
                                        '今天': [moment(), moment()],
                                        '最近一周': [moment().startOf('week'), moment().endOf('week')],
                                        '最近一个月': [moment().startOf('month'), moment().endOf('month')],
                                        '最近三个月': [moment(new Date()).subtract(3, 'months'), moment().endOf('month')]
                                    }}
                                />
                            </div>
                    }
                </div >
            )
        }, [buildings, floors, rooms, students])

        useEffect(() => {
            getBuildings()
        }, [])
        return (
            <InnerComponent {...props} render={Selects} groupId={{ buildingId, floorId, roomId, userId }} date={date}></InnerComponent>
        )
    }
}
//判断新注册学生是否填写信息
export function withStudent(InnerComponent) {
    return function OuterComponent(props) {
        let userInfo = localStorage.getItem('userInfo')
        try {
            userInfo = JSON.parse(userInfo) || {}
        } catch (err) {
            userInfo = {}
        }
        if (userInfo.name) {
            return <InnerComponent {...props} />
        } else {
            return <Redirect to={'/subject/dashboard'} />
        }
    }
}